import datetime

import shortuuid

from ..database import database
from ..models.auth import Auth
from ..models.local_auth import LocalAuth
class AuthService(object):
    @classmethod
    def _encrypt_password(cls, password):
        import hashlib
        sha256 = hashlib.sha256()
        sha256.update(password.encode())
        return sha256.hexdigest()

    @classmethod
    def is_local_auth_exist(cls, login_name):
        local_auth = LocalAuth.query.filter(LocalAuth.login_name == login_name).first()
        return local_auth is not None

    @classmethod
    def create_local_auth(cls, login_name, password, type, profile_id, *args, **kwargs):
        auth = Auth(id=shortuuid.uuid(), profile_id=profile_id)
        kwargs.update({
            'login_name': login_name,
            'password': cls._encrypt_password(password),
            'type': type,
        })
        local_auth = LocalAuth(**kwargs)

        local_auth.auth = auth
        database.session.add(local_auth)
        database.session.commit()
        return local_auth

    @classmethod
    def save_local_auth(cls, local_auth):
        local_auth.updated_time = datetime.datetime.now()
        database.session.add(local_auth)
        database.session.commit()



    @classmethod
    def fetch_local_auth_by_login_name(cls, login_name):
        return LocalAuth.query.filter(LocalAuth.login_name == login_name).first()

    @classmethod
    def delete_local_auth(cls, **kwargs):
        local_auth = LocalAuth.query.filter_by(**kwargs)
        if local_auth:
            local_auth.delete()
            database.session.commit()
